package com.qf.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

/**
 * @ClassName JdbcConfig
 * @Description TODO
 * @Author 86181
 * @Date 2022/8/30 19:17
 * @Version 1.0
 **/
@Configuration//指定当前类是一个配置类 当配置类作为AnnotationConfigApplicationContext
//对象创建参数时,该注解可以不写
//@ComponentScan("com.qf")
@PropertySource(value = "classpath:jdbc.properties")
public class JdbcConfig {
    @Value("${driverClass}")
   private String driverClass;
    @Value("${jdbcUrl}")
   private String jdbcUrl;
    @Value("${user}")
   private String user;
    @Value("${password}")
   private String password;

    /**
     * 使用IOC容器管理QueryRunner
     */
    @Bean(name = "runner")
    /**
     * 将当前方法的返回值注入IOC容器
     */
    @Scope(value = "prototype")//将QueryRunner改为多例
    public QueryRunner queryRunner() {
       return new QueryRunner(dataSource());



    }

    @Bean
    public DataSource dataSource() {
        DataSource dataSource = new ComboPooledDataSource();
        try {

            ((ComboPooledDataSource) dataSource).setDriverClass(driverClass);

            ((ComboPooledDataSource) dataSource).setJdbcUrl(jdbcUrl);

            ((ComboPooledDataSource) dataSource).setUser(user);

            ((ComboPooledDataSource) dataSource).setPassword(password);
            return dataSource;
        } catch (PropertyVetoException e) {
            throw new RuntimeException();
        }
    }

}
